<?php

namespace App\Api\Controllers;

use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class ApiController
{

    protected $apiDomain = 'http://dtrd.dtx-tech.com/jeecg-boot/';
    protected $testApiDomain = 'http://api.test.dtx-tech.com/jeecg-boot/';
    protected $allowMethod = ['get', 'post'];

    public function transfer(Request $request)
    {
        $callback = $request->get('callback');
        $url = $request->get('url');
        $method = $request->get('method', 'get');
        $payload = $request->get('payload');
        $contains = Str::contains($callback, '.test.');
        $apiDomain = $contains ? $this->testApiDomain : $this->apiDomain;

        $apiUrl = $apiDomain . $url;

        $payload = json_decode($payload, true);

        Log::info('apiPayload=====' .$url .'：',  $payload);

        if (!in_array($method, $this->allowMethod)) return json_encode(['success' => false, 'message' => '非法请求']);

        $client = new Client(['headers' => ['Content-Type' => 'application/json']]);
        $res = $client->request($method, $apiUrl, [
            $method == 'get' ? 'query' : 'json' => $payload
        ]);

        $body = $res->getBody(); //获得接口返回的主体对象
        return $body->getContents(); //获得主体内容
    }
}